package com.rickpan.service.impl;

import com.rickpan.entity.Tag;
import com.rickpan.repository.TagRepository;
import com.rickpan.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 标签服务实现
 * 
 * @author RickPan Team
 * @since 2024-01-06
 */
@Slf4j
@Service
@Transactional
public class TagServiceImpl implements TagService {

    @Autowired
    private TagRepository tagRepository;

    @Override
    public Tag createTag(Long userId, String name, String color, String type) {
        // 检查标签名称是否重复
        Optional<Tag> existingTag = tagRepository.findByUserIdAndNameAndType(userId, name, type);
        if (existingTag.isPresent()) {
            throw new RuntimeException("标签名称已存在");
        }

        Tag tag = new Tag();
        tag.setUserId(userId);
        tag.setName(name);
        tag.setColor(color != null ? color : "#409EFF");
        tag.setType(type);
        tag.setUsageCount(0);
        tag.setCreatedAt(LocalDateTime.now());
        tag.setUpdatedAt(LocalDateTime.now());

        return tagRepository.save(tag);
    }

    @Override
    public Tag updateTag(Long tagId, Long userId, String name, String color) {
        Optional<Tag> optionalTag = tagRepository.findByIdAndUserId(tagId, userId);
        if (optionalTag.isPresent()) {
            Tag tag = optionalTag.get();
            
            // 检查新名称是否与其他标签重复
            if (name != null && !name.equals(tag.getName())) {
                Optional<Tag> existingTag = tagRepository.findByUserIdAndNameAndType(userId, name, tag.getType());
                if (existingTag.isPresent() && !existingTag.get().getId().equals(tagId)) {
                    throw new RuntimeException("标签名称已存在");
                }
                tag.setName(name);
            }
            
            if (color != null) {
                tag.setColor(color);
            }
            
            tag.setUpdatedAt(LocalDateTime.now());
            return tagRepository.save(tag);
        }
        throw new RuntimeException("标签不存在或无权访问");
    }

    @Override
    public boolean deleteTag(Long tagId, Long userId) {
        Optional<Tag> optionalTag = tagRepository.findByIdAndUserId(tagId, userId);
        if (optionalTag.isPresent()) {
            tagRepository.delete(optionalTag.get());
            return true;
        }
        return false;
    }

    @Override
    public Tag getTagDetail(Long tagId, Long userId) {
        Optional<Tag> optionalTag = tagRepository.findByIdAndUserId(tagId, userId);
        if (optionalTag.isPresent()) {
            return optionalTag.get();
        }
        throw new RuntimeException("标签不存在或无权访问");
    }

    @Override
    public List<Tag> getAllTags(Long userId) {
        return tagRepository.findByUserIdOrderByTypeAscUsageCountDescCreatedAtDesc(userId);
    }

    @Override
    public List<Tag> getTagsByType(Long userId, String type) {
        return tagRepository.findByUserIdAndTypeOrderByUsageCountDescCreatedAtDesc(userId, type);
    }

    @Override
    public List<Tag> searchTags(Long userId, String keyword) {
        return tagRepository.searchTags(userId, keyword);
    }

    @Override
    public List<Tag> getPopularTags(Long userId) {
        return tagRepository.findPopularTags(userId);
    }

    @Override
    public void incrementUsageCount(Long tagId, Long userId) {
        Optional<Tag> optionalTag = tagRepository.findByIdAndUserId(tagId, userId);
        if (optionalTag.isPresent()) {
            Tag tag = optionalTag.get();
            tag.setUsageCount(tag.getUsageCount() + 1);
            tag.setUpdatedAt(LocalDateTime.now());
            tagRepository.save(tag);
        }
    }

    @Override
    public TagStats getTagStats(Long userId) {
        long totalTags = tagRepository.countByUserId(userId);
        long fileTags = tagRepository.countByUserIdAndType(userId, "file");
        long noteTags = tagRepository.countByUserIdAndType(userId, "note");
        
        return new TagStats(totalTags, fileTags, noteTags);
    }
}
